/**
 * Created with  SublimeText
 * @Author:      Lyle
 * @DateTime:    2017-02-13 10:59:14
 * @Description: 
 */
import * as API from '../../api'
import filterDataPartMixin from '../../common/filterDataPartMixin'
import permissionPartMixin from '../../common/permissionPartMixin'

const state = {
    userInfo: JSON.parse(Unit.getSessionStorage("ms_myself") || '{}')
}

const mutations = {

    setUserInfo: function(state, data) {
        state.userInfo = data;
        data = filterDataPartMixin.methods.filterDataPartMixin_ReplacePrivatePhotos(data);
        Unit.setSessionStorage("ms_myself", JSON.stringify(state.userInfo));
    },

    replacePhotos: function(state, data) {
        let arr = data.type == 1 ? state.userInfo.private_pictures : state.userInfo.pictures,
            toIndex = 0,
            formIndex = data.index,
            toItem = arr[toIndex],
            formItem = arr[formIndex];

        arr.splice(toIndex, 1, formItem);
        arr.splice(formIndex, 1, toItem);

        if (data.type == 1) {
            state.userInfo.private_pictures = arr;
        } else {
            state.userInfo.pictures = arr;
            state.userInfo.photo = arr[0];
        }

        Unit.setSessionStorage("ms_myself", JSON.stringify(state.userInfo));
    },

    movePhotos: function(state, data) {
        let arr = data.type == 1 ? state.userInfo.private_pictures : state.userInfo.pictures,
            moveItem = arr[data.index];
        arr.splice(data.index, 1);
        if (data.type == 1) {
            state.userInfo.pictures.push(moveItem);
        } else {
            state.userInfo.private_pictures.push(moveItem);
        }
        Unit.setSessionStorage("ms_myself", JSON.stringify(state.userInfo));
    },

    deletePhotos: function(state, data) {
        let arr = data.type == 1 ? state.userInfo.private_pictures : state.userInfo.pictures;
        arr.splice(data.index, 1);
        if (data.type == 1) {
            state.userInfo.private_pictures = arr;
        } else {
            state.userInfo.pictures = arr;
        }
        Unit.setSessionStorage("ms_myself", JSON.stringify(state.userInfo));
    },

    changePhotoStatus: function(state, data) {
        state.userInfo.privacy_setting.photo_only_show_to_favorite = data.photo_only_show_to_favorite;
        state.userInfo.privacy_setting.photo_hide_to_gender = data.photo_hide_to_gender;
        Unit.setSessionStorage("ms_myself", JSON.stringify(state.userInfo));
    },

    changePrivatePhotoStatus: function(state, data) {
        state.userInfo.private_album_request_num = parseInt(state.userInfo.private_album_request_num) - 1;
        Unit.setSessionStorage("ms_myself", JSON.stringify(state.userInfo));
    },

    addPhoto: function(state, data) {
        let userObj = state.userInfo,
            photoType = data.photoType,
            img = data.response;
        if (photoType == 'public') {
            if (userObj.pictures.length > 0) {
                var mainPhoto = userObj.pictures.shift();
                userObj.pictures.unshift(img);
                userObj.pictures.unshift(mainPhoto);
            } else {
                userObj.pictures.unshift(img);
                userObj.photo = img;
            }
        } else if (photoType == 'private') {
            userObj.private_pictures.unshift(img);
        }
        Unit.setSessionStorage("ms_myself", JSON.stringify(userObj));
    },

    updateProfileStatus: function(state, data) {
        state.userInfo.account.hidden = data.hide;
        Unit.setSessionStorage('ms_myself', JSON.stringify(state.userInfo));
    },
}

const actions = {

    user_login({ commit, state }, that) {
        API.login({
            data: {
                username: that.username,
                password: that.password,
                confirm_number: that.confirmNumber
            },
            success: function(response) {
                //console.log('callback', response);
                let data = response;
                if (typeof(data.errcode) == 'undefined') {
                    commit('setUserInfo', response);
                }
                that.loginCallback(data);
            },
            complete: () => {
                that.loading = false;
            }
        });
    },

    user_syncLogin({ commit, state }, that) {
        API.login({
            data: {},
            success: function(response) {
                console.log('callback', response);
                let data = response;
                if (typeof(data.errcode) == 'undefined') {
                    commit('setUserInfo', response);
                }
                if (that) {
                    that.syncLoginCallback(data);
                }
            }
        });
    },

    user_loginOut({ commit, state }, that) {
        API.login_out({
            success: (response) => {
                //commit('setUserInfo', null);
                if (that && that.loginOutCallback) {
                    that.loginOutCallback();
                }
            },
            complete: () => {
                permissionPartMixin.methods.permissionPartMixin_BrowserClear();
            }
        });
    },

    user_setMainPhoto({ commit, state }, obj) {
        API.set_photo_order({
            data: {
                'from_id': obj.from_id,
                'to_id': obj.to_id,
                'private': obj.type
            },
            success: function(response) {
                if (response.results == 1) {
                    commit('replacePhotos', obj);
                    obj.callback();
                }
            }
        });
    },

    user_movePhoto({ commit, state }, obj) {
        API.move_photo({
            data: obj.data,
            success: function(response) {
                if (response.results == 1) {
                    commit('movePhotos', obj);
                    obj.callback();
                }
            },
            complete: function() {
                obj.complete ? obj.complete() : '';
            }
        });
    },

    user_deletePhoto({ commit, state }, obj) {
        //commit('deletePhotos', obj);
        //obj.callback();
        API.delete_photo({
            data: {
                'item_id': obj.item_id,
                'private': obj.type
            },
            success: function(response) {
                console.log(response);
                if (response.results == 1) {
                    commit('deletePhotos', obj);
                    obj.callback();
                }
            }
        });
    },

    user_changePhotoStatus({ commit, state }, obj) {
        API.privacy_setting({
            data: obj.data,
            success: (response) => {
                if (response.results == 1) {
                    commit('changePhotoStatus', response);
                }
                if (obj.callback) {
                    obj.callback(response);
                }
            },
            complete: function() {
                obj.complete ? obj.complete() : '';
            }
        });
    },

    user_uploadPhoto({ commit, state }, obj) {
        API.common_upload_img({
            data: obj.data,
            success: (response) => {
                if (response.status_code == 0) {
                    if (obj.photoType == 'private') {
                        response.icon = filterDataPartMixin.methods.filterDataPartMixin_ReplaceNeedAccessURL(response.icon);
                        response.picture = filterDataPartMixin.methods.filterDataPartMixin_ReplaceNeedAccessURL(response.picture);
                    }
                    obj.response = response;
                    commit('addPhoto', obj);
                }
                obj.callback(response);
            },
            complete: function() {
                obj.complete ? obj.complete() : '';
            }
        });
    },

    user_updateProfile({ commit, state }, obj) {
        let promise = new Promise(function(resolve, reject) {
            API.update_profile({
                data: obj.data,
                success: function(response) {
                    resolve(response);
                },
                complete: function() {
                    obj.complete ? obj.complete() : '';
                },
                error: function() {
                    reject();
                    obj.error ? obj.error() : '';
                }
            });
        });

        promise.then(function(data) {
            return obj.processData ? obj.processData(data) : '';
        }, function(err) {
            console.log('update_profile err', err);
        }).then(function(data) {
            if (data) {
                commit('setUserInfo', data);
                obj.callback ? obj.callback() : '';
            }
        });
    },

    user_updateProfileStatus({ commit, state }, obj) {
        API.set_hidden({
            data: obj.data,
            success: function() {
                commit('updateProfileStatus', obj.data);
                obj.callback();
            },
            complete: function() {
                obj.complete ? obj.complete() : '';
            },
            error: function() {
                obj.error ? obj.error() : '';
            }
        })
    },

    user_approvePrivateAlbumRequest({ commit, state }, obj) {
        API.approve_private_album_request({
            data: obj.data,
            success: (response) => {
                commit('changePrivatePhotoStatus', response);
                obj.callback();
            },
            complete: function() {
                obj.complete ? obj.complete() : '';
            }
        })
    },

    user_register({ commit, state }, obj) {
        API.register({
            data: obj.data,
            success: function(result) {
                if (result.account) {
                    commit('setUserInfo', result);
                }
                obj.callback(result);
            },
            complete: function() {
                obj.complete ? obj.complete() : '';
            }
        });
    },

    user_cacheUserInfo({ commit, state }, obj) {
        commit('setUserInfo', obj);
    },

}

const getters = {

    userGenderValue: state => {
        let data = '';
        if (!_.isEmpty(state.userInfo)) {
            let genderList = JSON.parse(Unit.getLocalStorage('ms_gender'));
            data = _.result(_.find(genderList, { 'value': state.userInfo.account.gender }), 'label');
        }
        return data
    },

    isGuest: state => {
        return (!_.isEmpty(state.userInfo)) && (parseInt(state.userInfo.status.isGuest) == 1) ? true : false;
    }

}

export default {
    state,
    getters,
    actions,
    mutations
}
